package com.palmind.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Hashtable;

/**
 * The class <code>StringManager</code> is used for loading string resources
 * according to the appointed language.
 * 
 * @author Jarod Yv
 */
public class StringManager {
	private static StringManager instance = null;
	// private String lang = null;
	private String name = null;
	private Hashtable stringTable = null;
	private boolean hasLoaded = false;

	// private StringManager(String lang) {
	// this.lang = lang;
	// hasLoaded = false;
	// }

	public static StringManager getInstance(String lang) {
		// if (instance != null) {
		// instance.setLang(lang);
		// } else {
		// instance = new StringManager(lang);
		// }
		if (instance == null)
			instance = new StringManager();
		return instance;
	}

	public static String get(String name) {
		return instance.getString(name);
	}

	// public void setLang(String lang) {
	// if (this.lang.equals(lang))
	// return;
	// this.lang = lang;
	// hasLoaded = false;
	// }

	public void load(String name) {
		if (this.name.equals(name) && hasLoaded)
			return;
		if (stringTable == null)
			stringTable = new Hashtable();
		else
			stringTable.clear();
		InputStream is = this.getClass().getResourceAsStream(
				"/strings/" + name + ".lang");
		try {
			byte[] buf = new byte[1024];
			int c = is.read(buf);
			StringBuffer sb = new StringBuffer();
			String key = null;
			do {
				String data = new String(buf, 0, c);
				int s = 0;
				for (int i = 0; i < data.length(); ++i) {
					char x = data.charAt(i);
					if (s == 0 && (x == '=' || x == '\t')) {
						key = sb.toString();
						sb.delete(0, sb.length());
						s = 1;
					} else if (s == 1 && x == '\n') {
						if (key != null && key.length() > 0)
							stringTable.put(key, sb.toString());
						key = null;
						sb.delete(0, sb.length());
						s = 0;
					} else
						sb.append(x);
				}
			} while ((c = is.read(buf)) > 0);
			if (key != null && key.length() > 0)
				stringTable.put(key, sb.toString());
		} catch (Exception ex) {
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
				} finally {
					is = null;
				}
			}
		}
		this.name = name;
		this.hasLoaded = true;
	}

	public String getString(String name) {
		if (stringTable == null)
			return name;
		Object o = stringTable.get(name);
		if (o == null)
			return name;
		else
			return (String) o;
	}
}
